import { useAsyncEffect } from '@gnlab/utils/env-react'
import { message, Radio, Button } from 'antd'
import { ReactComponent as WorkFlowIcon } from '@/desktop/assets/workflow.svg'
import { EditModal, Empty } from '@/desktop/components'
import Loading from '@/desktop/components/Loading'
import services from '@/services'
import type { ChatFlow } from '@/services/features/chat-flows'
import './bind.module.less'

export default function BindChatFlow(props: {
  contactId: string | null
  forGroup: boolean
  onFinish: () => void
}) {
  const { contactId, forGroup, onFinish } = props
  return <EditModal open={contactId !== null} onCancel={onFinish} title="选择工作流" width="600px">
    {contactId !== null ? (
      <Content contactId={contactId} forGroup={forGroup} onFinish={onFinish} />
    ) : null}
  </EditModal>
}

function Content(props: { contactId: string; forGroup: boolean; onFinish: () => void }) {
  const { contactId, forGroup, onFinish } = props
  const [flows, setFlows] = useState<ChatFlow[] | null>(null)

  useAsyncEffect(async () => {
    const res = await services.features.chatFlows.load()
    if (res.success) setFlows(res.data.filter(v => v.forGroup === forGroup))
    else {
      void message.error(`工作流列表加载失败：${res.error}`)
      setFlows([])
    }
  }, [forGroup])

  const [choosed, setChoosed] = useState<number | null>(null)

  const [saving, setSaving] = useState(false)
  const save = useCallback(async () => {
    if (choosed === null) return

    setSaving(true)
    const res = await services.features.chatFlows.bind(contactId, choosed)
    setSaving(false)
    if (res.success) {
      void message.success('绑定成功')
      onFinish()
    } else {
      void message.error(`绑定失败：${res.error}`)
    }
  }, [contactId, choosed, onFinish])

  // ============================

  const empty = <div styleName="empty">
    <Empty description="没有可选择的工作流" />
  </div>

  if (!flows) return <Loading />
  if (!flows.length) return empty

  return <>
    <main styleName="flows">
      {flows.map(flow => <div styleName="flow" key={flow.id} onClick={() => setChoosed(flow.id)}>
        <Radio checked={choosed === flow.id} />
        <WorkFlowIcon />
        <div styleName="name">{flow.name}</div>
      </div>)}
    </main>
    <footer styleName="footer">
      <Button type="primary" disabled={choosed === null} onClick={save} loading={saving}>
        确定
      </Button>
    </footer>
  </>
}
